package com.quan.system.service.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.MailBean;
import com.quan.common.core.MyBaseServiceImpl;
import com.quan.common.utils.PasswordUtils;
import com.quan.common.utils.RandomUitl;
import com.quan.system.common.amqp.producer.ProducerMessageSendMail;
import com.quan.system.entity.SystemPermission;
import com.quan.system.entity.SystemRole;
import com.quan.system.entity.SystemUser;
import com.quan.system.mapper.SystemUserMapper;
import com.quan.system.service.SystemUserRoleService;
import com.quan.system.service.SystemUserService;

/**
 * <p>
 * 通用用户权限系统-用户表 服务实现类
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-03
 */
@Service
public class SystemUserServiceImpl extends MyBaseServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {

	@Autowired
	private SystemUserMapper mapper;
	
	@Autowired
	private ProducerMessageSendMail producerMessageSendMail;

	@Autowired
	private SystemUserRoleService userRoleService;

	@Override
	public boolean save(SystemUser entity) {
		// 加密盐
		entity.setSalt(RandomUitl.uuid());
		String password = RandomUitl.generateInteger(6); // 生成6位随机密码
		entity.setPassword(PasswordUtils.encodePassword(password, entity.getSalt()));
		boolean flag = super.save(entity);

		if (flag) {
			if(entity.getStatus()) { // 用户状态为正常才发送邮件
				// 发送短信或邮件告知用户账号和密码
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("subject", "综合管理系统.密码初始化");
				map.put("realname", entity.getRealname());
				map.put("username", entity.getUsername());
				map.put("password", password);
				
				MailBean mailBean = new MailBean();
				mailBean.setTo(entity.getEmail());
				mailBean.setSubject(map.get("subject").toString());
				mailBean.setTemplateLocation("mail/account.html");
				mailBean.setTemplateData(map);
				
				this.producerMessageSendMail.sender(mailBean);
			}
		}

		return flag;
	}
	
	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList) {
		boolean falg = super.removeByIds(idList);
		
		idList.forEach(id -> {
			this.userRoleService.deleteByUserId(id);
		});
		
		return falg;
	}

	// @Cacheable(value = "user", key = "#id")
	@Override
	public SystemUser getById(Serializable id) {
		return super.getById(id);
	}

	@Override
	public SystemUser findByUsername(String username) {
		SystemUser entity = new SystemUser();
		entity.setUsername(username);

		QueryWrapper<SystemUser> queryWrapper = new QueryWrapper<SystemUser>();
		queryWrapper.setEntity(entity);
		return super.getOne(queryWrapper);

	}

	@Override
	public List<SystemRole> findRolesByUserId(Long userId) {
		return this.mapper.findRolesByUserId(userId);
	}

	@Override
	public List<SystemPermission> findPermissionsByUserId(Long userId) {
		return this.mapper.findPermissionsByUserId(userId);
	}

	@Override
	public void updatePassword(Long id, String oldPassword, String newPassword) {
		SystemUser entity = super.getById(id);

		if (null != entity && entity.getId() != null) {
			if (!PasswordUtils.isPasswordValid(entity.getPassword(), oldPassword, entity.getSalt())) {
				throw new RuntimeException("新密码与原密码不一致");
			}

			String salt = RandomUitl.uuid();
			// 密码加盐组成加密密码
			String encodePassword = PasswordUtils.encodePassword(newPassword, salt);

			SystemUser newEntity = new SystemUser();
			newEntity.setId(id);
			newEntity.setPassword(encodePassword);
			newEntity.setSalt(salt);

			super.updateById(newEntity);
		} else {
			throw new RuntimeException("修改密码失败");
		}

	}

	@Override
	public boolean batchResetPassword(List<Long> idList) {
		boolean flag = true;
		if(null != idList && !idList.isEmpty()) {
			for (Long id : idList) {
				
				SystemUser entity = super.getById(id) ;
				// 加密盐
				entity.setSalt(RandomUitl.uuid());
				String password = "123456"; // 生成6位随机密码
				entity.setPassword(PasswordUtils.encodePassword(password, entity.getSalt()));
				
				flag = super.updateById(entity);
				
				if (flag) {
					// 发送短信或邮件告知用户账号和密码
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("subject", "综合管理系统.密码重置");
					map.put("realname", entity.getRealname());
					map.put("username", entity.getUsername());
					map.put("password", password);
					
					MailBean mailBean = new MailBean();
					mailBean.setTo(entity.getEmail());
					mailBean.setSubject(map.get("subject").toString());
					mailBean.setTemplateLocation("mail/account.html");
					mailBean.setTemplateData(map);
					
					this.producerMessageSendMail.sender(mailBean);
				}
			}
		}
		return flag;
	}

}
